package xyz.scootaloo.oj.leetcode

import java.lang.StringBuilder
import java.util.*

/**
 * @author flutterdash@qq.com
 * @since 2021/4/8 10:37
 */
class P385 {

    /**            [789]
     *       [456,       ]
     * [123,              , 123]
     */
    fun deserialize(s: String): NestedInteger {
        fun parserInt(str: StringBuilder): Int = Integer.parseInt(str.toString())
        fun clearCache(stack: Stack<NestedInteger>, cache: StringBuilder) {
            if (cache.isEmpty() || stack.isEmpty()) return
            stack.peek().setInteger(parserInt(cache))
            cache.setLength(0)
        }

        val cache = StringBuilder()
        val stack = Stack<NestedInteger>()

        for (current in s) {
            when {
                current.isDigit() -> { cache.append(current) }
                current == ',' -> { clearCache(stack, cache) }
                current == '[' -> {
                    val nextNestedInteger = NestedInteger()
                    if (!stack.isEmpty())
                        stack.peek().add(nextNestedInteger)
                    stack.push(nextNestedInteger)
                }
                current == ']' -> {
                    if (stack.size > 1)
                        stack.pop()
                }
            }
        }

        if (stack.isEmpty())
            return NestedInteger(parserInt(cache))
        return stack.pop()
    }

    class NestedInteger {
        // Constructor initializes an empty nested list.
        constructor()

        // Constructor initializes a single integer.
        constructor(value: Int)

        // @return true if this NestedInteger holds a single integer, rather than a nested list.
        fun isInteger(): Boolean {
            return false
        }

        // @return the single integer that this NestedInteger holds, if it holds a single integer
        // Return null if this NestedInteger holds a nested list
        fun getInteger(): Int? {
            return null
        }

        // Set this NestedInteger to hold a single integer.
        fun setInteger(value: Int): Unit {
        }

        // Set this NestedInteger to hold a nested list and adds a nested integer to it.
        fun add(ni: NestedInteger): Unit {

        }

        // @return the nested list that this NestedInteger holds, if it holds a nested list
        // Return null if this NestedInteger holds a single integer
        fun getList(): List<NestedInteger>? {
            return null
        }
    }

}
